package com.example.test.controller;

import com.example.test.entity.VerifyRequest;
import com.example.test.util.CaptchaCache;
import com.example.test.util.ImageClickCaptchaGenerator;
import com.example.test.util.ResultBean;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

// 生成验证码图片的接口
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @GetMapping("/image")
    public ResultBean generateCaptchaImage(HttpServletResponse response) throws IOException {
        try {
            ImageClickCaptchaGenerator.destroyed();
            BufferedImage captchaImage = ImageClickCaptchaGenerator.generateCaptchaImage();
            String captchaId = CaptchaCache.generateCaptchaId();
            List<Point> systemPoints = ImageClickCaptchaGenerator.getCorrectClickPoints();
            List<String> targetImages = ImageClickCaptchaGenerator.getTargetImages();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            System.out.println("系统图片坐标");
            System.out.println(systemPoints);
            CaptchaCache.put(captchaId, systemPoints);
            try {
                ImageIO.write(captchaImage, "png", byteArrayOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] imageBytes = byteArrayOutputStream.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            HashMap<String,Object> map = new HashMap<>();
            map.put("base64Image","data:image/png;base64," + base64Image);
            map.put("captchaId",captchaId);
            map.put("targetImages",targetImages);
            return ResultBean.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.error(500,"获取失败");
        }
    }

    @PostMapping("/verify/image-click")
    public boolean verifyImageClickCaptcha(@RequestBody VerifyRequest request) {
        String captchaId = request.getCaptchaId();
        List<Point> userClickPoints = request.getUserClickPoints();
        List<Point> systemPoints = CaptchaCache.get(captchaId);
        int errorRadius = 25;
        if (systemPoints == null || userClickPoints == null || userClickPoints.size() != systemPoints.size()) {
            return false;
        }
        return ImageClickCaptchaGenerator.isAreaMatch(systemPoints,userClickPoints,errorRadius);
    }

}

